package thingapi

import (
	"bytes"
	"fmt"
	"iot-base/common/common"
	"iot-base/common/dbconn"
	"iot-base/common/dbobj"
	rc "iot-base/common/redis"
	"iot-base/common/webapi"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

func recursionAddAreas(areaData []interface{}, parentID string, parentName string) {
	length := len(areaData)
	if length == 0 {
		return
	}
	data := make([]*dbobj.Area, 0, length)
	for _, v := range areaData {
		info := v.(map[string]interface{})
		countryArea := &dbobj.Area{
			Adcode:    info["adcode"].(string),
			SName:     info["name"].(string),
			Level:     info["level"].(string),
			WholeName: parentName + "/" + info["name"].(string),
			ParentID:  parentID,
		}
		switch info["citycode"].(type) {
		case string:
			countryArea.CityCode = info["citycode"].(string)
		default:
			countryArea.CityCode = ""
		}
		center := strings.Split(info["center"].(string), ",")
		//countryArea.SName = countryArea.WholeName

		countryArea.Lon = center[0]
		countryArea.Lat = center[1]
		countryArea.UID = countryArea.Adcode
		if countryArea.Level == "street" {
			countryArea.UID = countryArea.UID + "." + countryArea.SName
		}
		//countryArea.AreaKey = countryArea.Lon + "," + countryArea.Lat + "_" + countryArea.Adcode

		data = append(data, countryArea)
		if countryArea.Level == "country" {
			break
		}
		districts := info["districts"].([]interface{})
		if len(districts) > 0 {
			recursionAddAreas(districts, countryArea.UID, countryArea.WholeName)
		}
	}
	err := areaBatchSave(data)
	if err != nil {
		fmt.Println("recursionAddAreas", err)
	}

}

func areaBatchSave(emps []*dbobj.Area) error {
	var buffer bytes.Buffer
	sql := "INSERT INTO areas (s_name,uid,parent_id,level,whole_name,lon,lat,city_code,adcode,pin_yin,simple_py,per_pin_yin,path,zip_code) VALUES "
	if _, err := buffer.WriteString(sql); err != nil {
		return err
	}
	for i, e := range emps {

		if i == len(emps)-1 {
			buffer.WriteString(fmt.Sprintf("('%s','%s','%s','%s','%s','%s','%s','%s','%s','','','','','');",
				e.SName, e.UID, e.ParentID, e.Level, e.WholeName, e.Lon, e.Lat, e.CityCode, e.Adcode))
		} else {
			buffer.WriteString(fmt.Sprintf("('%s','%s','%s','%s','%s','%s','%s','%s','%s','','','','',''),",
				e.SName, e.UID, e.ParentID, e.Level, e.WholeName, e.Lon, e.Lat, e.CityCode, e.Adcode))
		}
	}
	return dbconn.DBConnection.Exec(buffer.String()).Error
}

const key = "29099d583b84fd176c7b56f5d84f7772"

//29099d583b84fd176c7b56f5d84f7772

func initAreaAPI(api *gin.RouterGroup) {
	// 从高德地图同步数据.
	api.POST("/areaSync", func(c *gin.Context) {
		// 防止重复提交
		key := "areas:sync"
		isLock, _ := rc.SetNX(key, 1, time.Second*5).Result()
		if !isLock {
			webapi.SendError("请勿重复提交", webapi.RedisError, c)
			return
		}
		defer func() {
			rc.Del(key)
		}()
		// 根据省获取
		result, err := common.GetGaudMapCode("29099d583b84fd176c7b56f5d84f7772", "中国", "1")
		if err != nil {
			webapi.SendError("获取坐标失败", webapi.RedisError, c)
			return
		}
		districts := result["districts"].([]interface{})
		//db, _ := dbconn.DBConnection
		recursionAddAreas(districts, "0", "中国")

		info := districts[0].(map[string]interface{}) //国家
		for _, value := range info["districts"].([]interface{}) {
			temp := value.(map[string]interface{}) //省
			province, err := common.GetGaudMapCode("29099d583b84fd176c7b56f5d84f7772", temp["name"].(string), "3")
			if err != nil {
				continue
			}
			districts = province["districts"].([]interface{})
			recursionAddAreas(districts, info["adcode"].(string), "中国")
		}
		webapi.SendResult(gin.H{}, nil, c)
		return
	})
}
